'use strict';

const path = require('path');
require('dotenv').config();

module.exports = appInfo => {
  const config = {};

  config.proxy = true;
  config.ipHeaders = 'x-real-forwarded-for,x-forwarded-for,client-ip';
  config.name = appInfo.name;
  // use for cookie sign key, should change to your own and keep security
  config.keys = appInfo.name + '_1520911541410_4096';
  config.debug = process.env.APP_DEBUG || 'false'; // 是否为debug状态
  config.schedulOpenStatus = process.env.SCHEDUL_OPEN;
  config.cluster = {
    listen: {
      path: '',
      port: parseInt(process.env.SERVER_PORT) || 7008,
      hostname: '0.0.0.0',
    }
};
config.onerror = {
  json(err, ctx) {
    const status = detectStatus(err);
    let errorJson = {};

    this.status = status;
    const code = err.code || err.type;
    const message = detectErrorMessage(ctx, err);

    ctx.status = code;
      if (status >= 500) {
        errorJson = {
          code,
          // don't respond any error message in production env
          message: http.STATUS_CODES[status],
        };


      } else {
        // 4xx client side error
        // addition `errors`
        errorJson = {
          code,
          message,
          errors: err.errors,
          expiredIn: err.expiredIn,
        };
      }

      ctx.set({
        "Content-Type": "application/json"
      });

      ctx.body = errorJson;
  },
};

  config.security = {
    csrf: {
      enable: false,
    },
  };
  config.bodyParser = {
    jsonLimit: '30mb',
    formLimit: '30mb',
  };
  // 配置商家信息
  config.tinfor = {
      key: process.env.T_APP_KEY,
      secrect: process.env.T_APP_SECRET
  };



  config.logger = {
    level: 'DEBUG',
    consoleLevel: 'DEBUG',
    dir: path.join(appInfo.baseDir, 'logs', `${appInfo.name}`),
  };


  config.api = require('./api.sit')(appInfo);
  return config;
};


function detectStatus(err) {
  let status = err.status || 500;
  if (status < 200) {
    // invalid status consider as 500, like urllib will return -1 status
    status = 500;
  }
  return status;
}